package com.javacoo.xservice.base.support.handler.internal;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.javacoo.xservice.base.BaseRequest;
import com.javacoo.xservice.base.ErrorCodeConstants;
import com.javacoo.xservice.base.bean.SecurityBean;
import com.javacoo.xservice.base.config.Resources;
import com.javacoo.xservice.base.exception.IllegalParameterException;
import com.javacoo.xservice.base.support.auth.AuthServiceHolder;
import com.javacoo.xservice.base.support.security.SecurityHolder;
import com.javacoo.xservice.base.support.security.SignBean;
import com.javacoo.xservice.base.utils.LogUtil;
import com.javacoo.xservice.base.utils.ValidationUtils;

/**
 * 参数校验處理器
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年6月28日上午10:30:58
 */
@Component
public class ParamValidatorHandler extends AbstractHandler {
	@Override
	public void preHandle(Object input) {
		BaseRequest req = (BaseRequest)input;
		//appKey
		String appKey = req.getAppKey();
		//时间戳
		Long timestamp = req.getTimestamp();
        //校验请求体
        ValidationUtils.validate(req);
		// 时间差
		Long currentTime = System.currentTimeMillis();
		if (Math.abs(currentTime - timestamp) > appCoreSetting.getApiAccessAllowTime()) {
			throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_TIMESTAMP_EXPIRE));
		}
		//appKey合法性
        if(!appCoreSetting.getSecurityMap().containsKey(appKey)){
            throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_APPKEY_FAILURE));
        }
        //渠道有效性校验及参数校验
        AuthServiceHolder.getAuthService().ifPresent(authService -> {
            if(!authService.auth(req)){
                throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_APPKEY_FAILURE));
            }
            if(!authService.check(req)){
                throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_TRANS_SN_FAILURE));
            }
        });

		//验证签名
        SecurityBean securityBean = appCoreSetting.getSecurityMap().get(req.getAppKey());
		if(securityBean.isSign()){
			if (StringUtils.isBlank(req.getSign())) {
				throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_SIGN_IS_EMPTY));
			}
			validateSign(req,securityBean);
		}
	}
    /**
     * 索引
     * <li>自然排序</li>
     *
     * @author duanyong@jccfc.com
     * @date 2021/3/4 11:06
     * @return: int
     */
    @Override
    public int index() {
        return 1;
    }

    /**
	 * 签名校验
	 * <p>说明:</p>
	 * <li></li>
	 * @author DuanYong
	 * @since 2017年7月13日上午10:10:28
	 */
	private void validateSign(BaseRequest req,SecurityBean securityBean){
        LogUtil.info("接口上送的签名值:{}",req.getSign());
		String paramJson = req.getParameter().get().toString();
        SecurityHolder.getSignService().ifPresent(signService -> {
            boolean result = signService.verifySign(SignBean.builder().sign(req.getSign()).nonce(req.getNonce()).param(paramJson).secretkey(securityBean.getSecretKey()).timestamp(req.getTimestamp().toString()).build());
            if(!result){
                throw new IllegalParameterException(Resources.getMessage(ErrorCodeConstants.COMMON_REQ_PARAM_SIGN_FAILURE));
            }
        });
	}
}
